package org.healthy.utils.pub.tool;

import com.alibaba.fastjson.JSONObject;
import org.healthy.model.ReduceResult;
import org.healthy.utils.pub.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


public class ResponseTools {
    private static ResponseTools tool;
    private Logger logger;


    public ResponseTools() {
        this.logger = LoggerFactory.getLogger(super.getClass());
    }

    public static ResponseTools get() {
        if (tool == null)
            tool = new ResponseTools();
        return tool;
    }

    private String buildBizInfo(Object info) {
        ReduceResult result = new ReduceResult();
        result.setSuccess(true);
        result.setDesc("success");
        result.setErrorCode("ok");
        result.setData(info);
        return JSONObject.toJSONString(result);
    }

    public  void responseResult(HttpServletResponse resp, String o) {
        PrintWriter pw = null;
        resp.setContentType("text/javascript;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        String value = o;
        try {
            pw = resp.getWriter();
            pw.write(value.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            pw.close();
        }
    }

    private String buildError(ServiceException e) {

        ReduceResult result = new ReduceResult();
        result.setSuccess(false);
        result.setDesc(e.getMessage());
        result.setErrorCode(e.getCode());
        return JSONObject.toJSONString(result);
    }

    private String buildExceError(Exception e) {

        ReduceResult result = new ReduceResult();
        result.setSuccess(false);
        result.setDesc(e.getMessage());
        result.setErrorCode("E1");
        return JSONObject.toJSONString(result);
    }

    private String responseInfo(Object info) {
        return buildBizInfo(info);
    }

    public void response(Object info, Object page) {
        if (info instanceof ServiceException)
            responseError((ServiceException) info, null);
        else if (info instanceof Exception)
            responseError(null, (Exception) info);
        else
            responseInfo(info);
    }

    public String response(Object info) {
        if (info instanceof ServiceException)
            return responseError((ServiceException) info, null);
        else if (info instanceof Exception)
            return responseError(null, (Exception) info);
        else
            return responseInfo(info);
    }

    private String responseError(ServiceException e,
                               Exception e1) {
        String obj = "";
        if (e != null)
            obj = buildError(e);
        else
            obj = buildExceError(e1);

        return obj;
    }
}